package com.rent.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rent.entity.WechatUser;
import com.rent.exception.BusinessException;
import com.rent.mapper.WechatUserMapper;
import com.rent.model.JsCode2SessionModel;
import com.rent.model.LoginResultModel;
import com.rent.model.WechatUserModel;
import com.rent.service.WeChatService;
import com.rent.service.WechatUserService;
import com.rent.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2021-06-05
 */
@Slf4j
@Service
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements WechatUserService {

    @Autowired
    private WeChatService weChatService;
    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Override
    public LoginResultModel wechatLogin(String code, String appid, String secret) {
        log.info("wechatLogin code:[{}]", code);
        JsCode2SessionModel wechatMsgByCode = this.weChatService.getWechatMsgByCode(code, appid, secret);
        if (wechatMsgByCode.isSuccess()) {
            throw new BusinessException(500, wechatMsgByCode.getErrcode() + wechatMsgByCode.getErrmsg());
        }
        WechatUser wechatUser = this.getByOpenId(wechatMsgByCode.getOpenid());
        LoginResultModel loginResultModel = new LoginResultModel();
        loginResultModel.setOpenId(wechatMsgByCode.getOpenid());
        loginResultModel.setWechatUserModel(this.transferFromWeChatUser(wechatUser));
        loginResultModel.setJwtToken(JwtUtil.getJWT(wechatMsgByCode.getOpenid()));
        return loginResultModel;
    }

    private WechatUserModel transferFromWeChatUser(WechatUser wechatUser) {
        if (wechatUser == null) {
            return null;
        }
        WechatUserModel wechatUserModel = new WechatUserModel();
        BeanUtils.copyProperties(wechatUser, wechatUserModel);
        return wechatUserModel;
    }

    @Override
    public WechatUser getByOpenId(String openId) {
        return wechatUserMapper.selectByOpenId(openId);
    }
}
